#include "stdAfx.h"
#include "Power.h"


Power::Power(void)
{
}


Power::~Power(void)
{
}

int Power::IntPower(int number,int exp){
	if(exp == 0 ){
		return 1;
	}
	bool isMinus = false;
	if(exp<0){
		exp = 0-exp;
		isMinus = true;
	}

	int result = GetPower(number,exp);
	if(isMinus){
		result = 1/result;
	}
	return result;
}

int Power::GetPower(int number,int exp){
	int result = 1;
	for(int i = 0;i<exp;i++){
		result = result*number;
	}
	return result;
}

bool Power::FloatEqual(double d1,double d2){
	if((d1-d2<0.0000001)&&(d1-d2)>-0.0000001){
		return true;
	}
	return false;
}

double Power::DoublePower(double base,int exp){
	if(exp == 0){
		return 1;
	}
	bool isNegative = false;
	if(exp<0){
		isNegative = true;
		exp = 0-exp;
	}
	double result = PowerRecursion(base,exp);
	
	if(isNegative){
		result = 1/result;
	}
	return result;
}

double Power::PowerRecursion(double base,int exp){
	if(exp == 0){  //exp&1 == 1
		return 1;
	}

	if(exp == 1){  //exp&1 == 1
		return base;
	}
	bool isOdd = false;
	double result =1;
	if((exp&0x1) == 1){
		isOdd = true;
		result = result*PowerRecursion(base,(exp-1)>>1);
	}else{
		result = result*PowerRecursion(base,exp>>1);
	}
	result = result * result;
	
	if(isOdd){
		result = result * base;
	}

	return result;
}
